package com.example.demo.concurrent.ThreadPoolTest;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-03-15
 * Time: 20:57
 */
public class MyBlockIngQueue<T> {
    //队列存放任务
    private Deque<T> queue = new ArrayDeque<>();
    //容量大小
    private int capacity;
    //锁对象
    private ReentrantLock lock = new ReentrantLock();
    //生产者条件变量
    Condition fullCondition = lock.newCondition();
    //消费者条件变量
    Condition emptyCondition = lock.newCondition();

    //阻塞添加任务
    public void put(T t) {
        lock.lock();
        try {
            while(queue.size() == this.capacity) {
                try {
                    fullCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.add(t);
            emptyCondition.signal();
        }finally {
            lock.unlock();
        }
    }
    //阻塞获取
    public T take() {
        lock.lock();
        try{
            while(queue.size() == 0) {
                try {
                    emptyCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T val = queue.poll();
            fullCondition.signal();
            return val;
        }finally {
            lock.unlock();
        }
    }
}